<?php

declare(strict_types=1);

namespace App\AdminApi\Modular\Data\Service;

use App\Common\Modular\Data\Enums\ResourcesCateState;
use App\Common\Modular\Data\Model\ResourcesCateModel;
use App\Common\Modular\Data\Serve\ResourceCateServe;
use Core\Constants\Database;
use Zms\Exception\AppException;
use Core\Package\ElementPlus\FormCreate\Form;
use Core\Package\ElementPlus\FormCreate\FormItem;

/**
 * 资源服务层
 * Class BannerService
 */
class ResourcesCateService extends ResourceCateServe
{

    /**
     * 创建资源分类表单
     * @throws AppException
     */
    public function createdResourcesCateForm($type = ''): Form
    {
        if (ResourcesCateState::Exists($type, ResourcesCateState::TAG['TYPE'])) {
            $rule[] = FormItem::Hidden('type', $type);
            $rule[] = FormItem::Input('name', '分类名称')->placeholder('资源分类名称')->clearable(true)->maxlength(10)->required('请输入分类名称');
            $rule[] = FormItem::Number('sort', '分类排序')->placeholder('分类越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
            return Form::create('添加资源分类')->setRules($rule)->setOptionFormInline(true);
        }
        throw new AppException('数据异常,请输入新重试');
    }


    /**
     * 创建资源分类表单
     * @throws AppException
     */
    public function updatedResourcesCateForm($id = ''): Form
    {
        /**
         * @var $cate ResourcesCateModel
         */
        $cate = $this->search()->where(['id' => $id])->first();
        if ($id && $cate) {
            $rule[] = FormItem::Hidden('id', $cate->id);
            $rule[] = FormItem::Input('name', '分类名称', $cate->name)->placeholder('资源分类名称')->clearable(true)->maxlength(10)->required('请输入分类名称');
            $rule[] = FormItem::Number('sort', '分类排序', $cate->sort)->placeholder('分类越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
            return Form::create('编辑资源分类')->setRules($rule)->setOptionFormInline(true);
        }
        throw new AppException('分类不存在或已删除');
    }


    /**
     * 获取资源分类
     * @param array $where
     * @return array
     */
    public function getResourcesCate(array $where): array
    {
        return $this->search($where)->select(['id', 'name'])->orderByRaw('sort DESC,id ASC')->get()->toArray();
    }

}